#!/usr/bin/env python
# coding=utf-8

# File Name: recieve.py
# Author: Bill Zhang
# Mail: zchcandid@gmail.com 
# Created Time: Fri 29 Nov 2013 03:08:41 PM CST
import pika
import time
from libUpdate import UpdateClass
import simplejson as json
import pymongo

def callback(ch, method, properties, body):
    """This is callback function:
    Some conversion is as follows:
        UC=UpdateClass
        IU=ID and URL
        QP=quantity and price
    The wrong code:
        if can not read the html code: "Q":-1
        if can not parse the html code: "Q1":-1
    
    """
   #body=body.decode(body)
    body=body.decode('utf-8')
   # print(body)
   # time.sleep( body.count('.')  )
    #body is json formate:{"ID":1,"URL":"http://www.digikey.cn..."}
    IU=json.loads(body)

    print("get line 32 goUpdate.py")    
    print(IU["ID"])
    URL=IU["URL"]
    UC=UpdateClass()
    if UC is 'W':
        print("Something wrong detected when init the UpdateClass")
        log=open("log/update.log","a")
        log.write("Something wrong detected when init the UpdateClass")
        log.close()
        
        print("get line 42 goUpdate.py")    
        data={"HQID":IU["ID"],"URL":IU["URL"],"Q":0,"Q1":-1,"P1":0}    
        saving(data)
        ch.basic_ack(delivery_tag = method.delivery_tag)
        return 0

    HtmlCode=UC.getCode(URL)
    #when run success HtmlCode will be (0,0)
    if HtmlCode is not 'Y':
        print("Something wrong detected:%s %s" % (HtmlCode[0],URL))
        log=open("log/update.log","a")
        log.write("\nOther wrong detected,ID:%s,URL:%s,R:%s\n" % (str(IU["ID"]),URL,HtmlCode[1]))
        log.close()
        data={"HQID":IU["ID"],"URL":IU["URL"],"Q":-1,"Q1":0,"P1":0}    
        saving(data)
        ch.basic_ack(delivery_tag = method.delivery_tag)
        return 0
    errorCode=UC.toUpdate(1)
    if errorCode is 'W':
        print("Something wrong detected when parse the html code")
        log=open("log/update.log","a")
        log.write("Something wrong detected when parse the html code")
        log.close()
        data={"HQID":IU["ID"],"URL":IU["URL"],"Q":0,"Q1":-1,"P1":0}    
        saving(data)
        ch.basic_ack(delivery_tag = method.delivery_tag)
        return 0
    QP=UC.ProductPrice
    data=formateData(IU,QP)
    #存入数据库
    saving(data)
    ch.basic_ack(delivery_tag = method.delivery_tag)
def recieve():
    print("Icmal collection center has been runing!")
    connection = pika.BlockingConnection(pika.ConnectionParameters( host = 'localhost' ))
    channel = connection.channel()
    channel.queue_declare(queue = 'icmall' , durable = True )
    channel.basic_qos(prefetch_count = 1 )
    channel.basic_consume(callback,queue = 'icmall')
    channel.start_consuming()
def saving(data):
    uri="mongodb://hqjf:aa88OO00@192.168.100.58:8888/digikey"
    try:
        con=pymongo.MongoClient(uri)
        db=con.digikey
        db.update.insert(data)
    except pymongo.errors.ConnectionFailure:
        print("fail to connect mongodb,try after 3s")
        time.sleep(3)
        con=pymongo.MongoClient(uri)
    except pymongo.errors.ConfigurationError:
        print("Your password config is not right,fail to connect mongodb!")
        print("The formate should be 'mongodb://user:password@example.com/the_database'")
        print("Please try again!")
    except pymongo.errors.InvalidURI:
        print("Your uri is not write,fail to connect mongodb!")
        print("The formate should be 'mongodb://user:password@example.com/the_database'")
        print("Please try again!")
    except pymongo.errors.AutoReconnect(message='Lose connection,reconnect.....', errors=None):
        print("reconnect .......")

def formateData(IU,QP):
    #lenth of Quantity and price
    if(isinstance(QP,list)):
        i=len(QP) 
    else:
        i=0
    if(i==0):
        data={"HQID":IU["ID"],"URL":IU["URL"],"Q":0,"Q1":0,"P1":0}    
    if(i==3):
        data={"HQID":IU["ID"],"URL":IU["URL"],"Q":QP[0],"Q1":QP[1],"P1":QP[2]}    
    elif(i==5):
        data={"HQID":IU["ID"],"URL":IU["URL"],"Q":QP[0],"Q1":QP[1],"P1":QP[2],"Q2":QP[3],"P2":QP[4]}    
    elif(i==7):
        data={"HQID":IU["ID"],"URL":IU["URL"],"Q":QP[0],"Q1":QP[1],"P1":QP[2],"Q2":QP[3],"P2":QP[4],"Q3":QP[5],"P3":QP[6]}    
    elif(i==9):
        data={"HQID":IU["ID"],"URL":IU["URL"],"Q":QP[0],"Q1":QP[1],"P1":QP[2],"Q2":QP[3],"P2":QP[4],"Q3":QP[5],"P3":QP[6],"Q4":QP[7],"P4":QP[8]}    
    elif(i==11):
        data={"HQID":IU["ID"],"URL":IU["URL"],"Q":QP[0],"Q1":QP[1],"P1":QP[2],"Q2":QP[3],"P2":QP[4],"Q3":QP[5],"P3":QP[6],"Q4":QP[7],"P4":QP[8],"Q5":QP[9],"P5":QP[10]}    
    elif(i==13):
        data={"HQID":IU["ID"],"URL":IU["URL"],"Q":QP[0],"Q1":QP[1],"P1":QP[2],"Q2":QP[3],"P2":QP[4],"Q3":QP[5],"P3":QP[6],"Q4":QP[7],"P4":QP[8],"Q5":QP[9],"P5":QP[10],"Q6":QP[11],"P5":QP[12]}    
    elif(i==15):
        data={"HQID":IU["ID"],"URL":IU["URL"],"Q":QP[0],"Q1":QP[1],"P1":QP[2],"Q2":QP[3],"P2":QP[4],"Q3":QP[5],"P3":QP[6],"Q4":QP[7],"P4":QP[8],"Q5":QP[9],"P5":QP[10],"Q6":QP[11],"P5":QP[12],"Q7":QP[13],"P7":QP[14]}    
    elif(i==17):
        data={"HQID":IU["ID"],"URL":IU["URL"],"Q":QP[0],"Q1":QP[1],"P1":QP[2],"Q2":QP[3],"P2":QP[4],"Q3":QP[5],"P3":QP[6],"Q4":QP[7],"P4":QP[8],"Q5":QP[9],"P5":QP[10],"Q6":QP[11],"P5":QP[12],"Q7":QP[13],"P7":QP[14],"Q8":QP[15],"P8":QP[16]}    
    elif(i==19):
        data={"HQID":IU["ID"],"URL":IU["URL"],"Q":QP[0],"Q1":QP[1],"P1":QP[2],"Q2":QP[3],"P2":QP[4],"Q3":QP[5],"P3":QP[6],"Q4":QP[7],"P4":QP[8],"Q5":QP[9],"P5":QP[10],"Q6":QP[11],"P5":QP[12],"Q7":QP[13],"P7":QP[14],"Q8":QP[15],"P8":QP[16],"Q9":QP[17],"P9":QP[18]}    
    elif(i==21):
        data={"HQID":IU["ID"],"URL":IU["URL"],"Q":QP[0],"Q1":QP[1],"P1":QP[2],"Q2":QP[3],"P2":QP[4],"Q3":QP[5],"P3":QP[6],"Q4":QP[7],"P4":QP[8],"Q5":QP[9],"P5":QP[10],"Q6":QP[11],"P5":QP[12],"Q7":QP[13],"P7":QP[14],"Q8":QP[15],"P8":QP[16],"Q9":QP[17],"P9":QP[18],"Q10":QP[19],"P10":QP[20]}    
    else:
        data={"HQID":IU["ID"],"URL":IU["URL"],"Q":0,"Q1":0,"P1":0}    

    return data



#debug mode
if __name__=="__main__":
    """
    ---if __name=="__main__"-----
    This is for debug this moudle,
    When run this moudle as the main 
    the code below will run
    """
    uri="mongodb://hqjf:aa88OO00@192.168.100.58:8888/digikey"
    try:
        con=pymongo.MongoClient(uri)
    except pymongo.errors.ConnectionFailure:
        print("fail to connect mongodb,try after 3s")
#        time.sleep(3)
        con=pymongo.MongoClient(uri)
    except pymongo.errors.InvalidURI:
        print("Your uri is not write,fail to connect mongodb!")
        print("The formate should be 'mongodb://user:password@example.com/the_database'")
        print("Please try again!")
    db=con.digikey
   # i=db.update.find()
   # print(list(i))
    a='{"ID":1,"URL":"www.baidu.com"}'
    b=json.loads(a)
    print(b)
    print(b["ID"])
